package com.example.cursor_service.impl;

import com.example.cursor_service.UserService;
import com.example.cursor_orm.model.User;
import com.example.cursor_orm.dao.UserDAO;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.ArrayList;
import com.example.cursor_orm.util.PasswordUtil;

@Service
public class UserServiceImpl implements UserService {
    private final UserDAO userDAO;
    
    public UserServiceImpl(UserDAO userDAO) {
        this.userDAO = userDAO;
    }
    
    @Override
    public User createUser(User user) {
        try {
            // 注册时生成随机salt并加密密码
            String salt = com.example.cursor_orm.util.PasswordUtil.generateSalt();
            String hash = com.example.cursor_orm.util.PasswordUtil.hashPassword(user.getPasswordHash(), user.getSalt());
            user.setSalt(salt);
            user.setPasswordHash(hash);
            userDAO.insert(user);
            return user;
        } catch (Exception e) {
            return null;
        }
    }
    
    @Override
    public User getUserById(Integer id) {
        try {
            return userDAO.findById(id);
        } catch (Exception e) {
            return null;
        }
    }
    
    @Override
    public User updateUser(Integer id, User user) {
        try {
            user.setId(id);
            userDAO.update(user);
            return userDAO.findById(id);
        } catch (Exception e) {
            return null;
        }
    }
    
    @Override
    public boolean deleteUser(Integer id) {
        try {
            return userDAO.deleteById(id) > 0;
        } catch (Exception e) {
            return false;
        }
    }
    
    @Override
    public List<User> getUserList(int page, int size) {
        try {
            List<User> all = userDAO.findAll();
            int from = Math.max(0, (page - 1) * size);
            int to = Math.min(all.size(), from + size);
            return all.subList(from, to);
        } catch (Exception e) {
            return new ArrayList<>();
        }
    }
    

    
    /**
     * 用户登录
     * @param username 用户名（由Controller层User对象传递）
     * @param password 密码（由Controller层User对象传递）
     */
    @Override
    public User login(String username, String password) {
        try {
            User user = userDAO.findByUsername(username);
            if (user != null) {
                // 只用BCrypt校验，不要再hash一次
                if (PasswordUtil.checkPassword(password, user.getPasswordHash())) {
                    return user;
                }
            }
            return null;
        } catch (Exception e) {
            return null;
        }
    }
    
    @Override
    public void logout(Integer userId) {
        // 可记录登出日志等
        // 这里暂时不实现具体逻辑
    }
    
    @Override
    public boolean resetPasswordRequest(String username) {
        try {
            // 这里只做伪实现，实际应发送邮件或短信
            return userDAO.existsByUsername(username);
        } catch (Exception e) {
            return false;
        }
    }
    
    @Override
    public boolean updatePassword(Integer userId, String oldPassword, String newPassword) {
        try {
            User user = userDAO.findById(userId);
            if (user == null || !user.getPasswordHash().equals(oldPassword)) return false;
            user.setPasswordHash(newPassword);
            return userDAO.update(user) > 0;
        } catch (Exception e) {
            return false;
        }
    }
    
    @Override
    public String refreshToken(String refreshToken) {
        try {
            // 这里只做伪实现，实际应校验并生成新token
            return "newToken_" + System.currentTimeMillis();
        } catch (Exception e) {
            return null;
        }
    }
} 